# coding=utf-8
import time
import random
import string
import hashlib


class Sign:
    def __init__(self, jsapi_ticket, url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': jsapi_ticket,
            'timestamp': self.__create_timestamp(),
            'url': url
        }

    def __create_nonce_str(self):
        return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))

    def __create_timestamp(self):
        return int(time.time())

    def sign(self):
        string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
        self.ret['signature'] = hashlib.sha1(string).hexdigest()
        return self.ret

    def sign_param(self, dict):
        dict["appId"] = "wx3d857b42797b5eb4"
        dict["nonceStr"] = self.__create_nonce_str()
        dict["timeStamp"] = self.__create_timestamp()
        string = '&'.join(['%s=%s' % (key.lower(), dict[key]) for key in sorted(dict)])
        string = string + "&key=xz2X31GP1zfoSfOWq4gPqwDdaD6Ggl3Q"
        dict["signature"] = hashlib.sha1(string).hexdigest()
        return dict
